<?php

namespace App\FrontModule\Presenters;

use \Nette\Application\Responses\JsonResponse;

/**
 * Lesson presenter
 * @author jirka
 */
class LessonsPresenter extends BasePresenter {

  /** @var \App\Model\VideoManager @inject */
  public $vm;
  
  /** @var \App\Model\UserManager @inject */
  public $um;
  
	/** @var video is video object prepare for template */
	private $video = null;
  
  private $relatedVideos = null;

  /**
   * Action for video detail
   * @param String $name
   */
	public function actionDetail($name = "") {
		$this->video = $this->vm->getVideoByWebalize($name);
    
    if(!$this->video){
      $this->redirect('Homepage:default');
    }
	}
  
  /**
   * Render for video detail
   * @param String $name
   */
  public function renderDetail($name = "") {
		$this->template->video = $this->video;
    $this->template->commentsCount = $this->vm->getVideoCommentsCount($this->video);
    $this->template->viewsCount = $this->vm->getVideoViewsCount($this->video);
    
    $related = $this->vm->getRelatedVideosArray($this->video->getLearn(), 4);
    
    if(count($related) == 0){
      $related = $this->vm->getRelatedVideosArrayDesc($this->video->getLearn(), 4, true);
    }
    
    $this->template->relatedVideos = $related;
	}

  /**
   * JSON all videos 
   */
	public function handleGetLessons() {
		if ($this->isAjax()) {
			$this->sendResponse(new JsonResponse($this->vm->getAllVideosBaseArray()));
		}
	}
  
  /**
   * Handle for add video request
   */
  public function handleAddView(){
    if($this->isAjax()){
      // Get last view of video by user ip 
      $ip = \App\Model\UserManager::getUserIp();
      
      $viewDao = $this->em->getDao(\App\Model\Dao\VideoView::getClassName());
      $lastView = $viewDao->findOneBy(array('ip' => $ip, 'video' => $this->video), array('watched' => 'DESC'));
      $watched = new \DateTime();
      
      // If video not be viewed from user ip. Or was but before long time
      if(!$lastView || (($lastView->getWatched()->format('U') + 1000) < $watched->format('U'))){
        $newView = new \App\Model\Dao\VideoView();
        
        if($this->user->isLoggedIn()){
          $user = $this->um->getUserById($this->user->getId());
          $newView->setAll($this->video, $ip, $watched, $user);
        }else{
          $newView->setAll($this->video, $ip, $watched);
        }
        
        $this->em->persist($newView);
        $this->em->flush();
        
        echo json_encode(array('status' => 'ok'));
      }else{
        echo json_encode(array('status' => 'no_ok'));
      }
      
      exit();
    }
  }
  
  /**
   * Comment component
   * @return \App\Component\Comment
   */
  public function createComponentComment(){
    $comment = new \App\Component\Comment();
    $comment->init($this->video, $this->em, 4);
    return $comment;
  }
}
